/** 注释
 * @Author FiveXu(316643470@qq.com)
 * @Description: browserHooks
 * @Date  2023-11-05 10:10
 */
import { nextTick, onBeforeMount, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import { useSystemSettingStore } from '@/stores/desk/systemSetting'
import { browserChannel, sleep } from '@/utils/utils'
import { useCreateTask } from '@/hooks/runningTaskHooks'
import { useRunningTasksStore } from '@/stores/taskBar/runningTasks'

export enum BrowserChannelType {
  isOtherId = 'isOtherId',
  sendOwnId = 'sendOwnId',
  createTask = 'createTask',
  refresh = 'refresh',
  taskMove = 'taskMove',
  resizeMove = 'resizeMove',
  dragEnd = 'dragEnd',
  setCurrentWin = 'setCurrentWin'
}

export const useBrowserHook = () => {
  const route = useRoute()
  const systemSettingStore = useSystemSettingStore()
  const runningTasksStore = useRunningTasksStore()
  const { handleCreateTask } = useCreateTask()

  // 创建Window窗口
  const createWindowInit = () => {
    setMainSize()
  }
  const setMainSize = () => {
    if (route.path === '/default/desk') {
      systemSettingStore.setMainDesk(outerWidth, outerHeight)
    } else if (route.path === '/default/expand') {
      systemSettingStore.setDeskLock(false)
    }
  }

  browserChannel.onmessage = async (ev) => {
    switch (ev.data.type) {
      case BrowserChannelType.createTask:
        if (route.path === '/default/expand') {
          handleCreateTask(ev.data.data)
          await sleep(1000)
          location.reload()
        }
        break
      case BrowserChannelType.refresh:
        await nextTick()
        location.reload()
        break
      case BrowserChannelType.taskMove: {
        const { appId, taskId, x, y } = ev.data.data
        const { mainDesk } = systemSettingStore.$state
        const disX = route.path === '/default/desk' && mainDesk[2] === 1 ? mainDesk[0] : 0
        runningTasksStore.setTaskPatch(appId, taskId, {
          x: x + disX,
          y,
          endX: x,
          endY: y,
          isDrag: true
        })
        break
      }
      case BrowserChannelType.resizeMove: {
        const { appId, taskId, width, height } = ev.data.data
        runningTasksStore.setTaskPatch(appId, taskId, {
          width,
          height,
          isDrag: true
        })
        break
      }
      case BrowserChannelType.dragEnd: {
        const { appId, taskId } = ev.data.data
        runningTasksStore.setTaskPatch(appId, taskId, {
          isDrag: false
        })
        break
      }
      case BrowserChannelType.setCurrentWin: {
        const { mainDesk } = systemSettingStore.$state
        systemSettingStore.setMainDesk(mainDesk[0], mainDesk[1], ev.data.data)
        break
      }
    }
  }

  onBeforeMount(() => {
    createWindowInit()
    window.addEventListener('resize', setMainSize)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', setMainSize)
  })
}
